﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WFNetLib;
using System.IO.Ports;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;
using WFNetLib.GSMModem;
using WFNetLib.Forms;
using WFNetLib.Net;
using System.IO;
using System.IO.Compression;
using System.Net;

namespace QueryBookTicket
{
    public class QueryBookTicketThread1
    {
        public SerialPort Com;
        public Thread ReaderThreadIns = null;
        public static event strEventHandler AddLogEvent;//事件声明
        public static event intstrEventHandler FinishEvent;//事件声明
#if DEBUG
        CommunicationDebugForm CommunicationDebugForm;
#endif


        GsmModem gsmModem;
        public string PortName;
        public int ComIndex;
        void OnAddLog(string strLog)
        {
            if (AddLogEvent != null)
            {
                AddLogEvent(this, new strEventArgs(strLog));
            }
        }
        void OnFinishEvent(int n)
        {
            if (FinishEvent != null)
            {
                FinishEvent(this, new intstrEventArgs(n));
            }
        }
        void OnFinishEvent(int n, string str)
        {
            if (FinishEvent != null)
            {
                FinishEvent(this, new intstrEventArgs(n, str));
            }
        }
        public QueryBookTicketThread1(SerialPort _Com, int index)
        {
            Com = _Com;

#if DEBUG
            CommunicationDebugForm = new CommunicationDebugForm();
            //CommunicationDebugForm.IsClose = true;
            CommunicationDebugForm.Show();
            CommunicationDebugForm.Text = Com.PortName + "数据检测";
            gsmModem = new GsmModem(Com, CommunicationDebugForm);
#else
            gsmModem = new GsmModem(Com);
#endif

            ComIndex = index;
            gsmModem.dIP[0] = 10;
            gsmModem.dIP[1] = 0;
            gsmModem.dIP[2] = 0;
            gsmModem.dIP[3] = 172;
            gsmModem.dPort = 80;
            gsmModem.AddLog += new strEventHandler(gsmModem_AddLog);

        }

        void gsmModem_AddLog(object sender, strEventArgs e)
        {
            OnAddLog(e.strArg);
        }
        public void ReaderThreadStart()
        {
            ReaderThreadIns = new Thread(new ThreadStart(ReaderProc));
            ReaderThreadIns.Name = "查询" + Com.PortName;
            PortName = Com.PortName;
            ReaderThreadIns.Start();
            OnAddLog("查询开始");
        }
        private void ReaderProc()
        {
            //try
            {
                while (true)
                {
                    try
                    {
                        Com.Open();
                        //Com.RtsEnable = true;
                    }
                    catch
                    {
                        OnAddLog("串口无法打开,请终止软件");
                        OnFinishEvent((int)FinishType.Unkown);
                        break;
                    }
                    if (!gsmModem.InitGSMModem())
                    {
                        break;
                    }
                    OnAddLog("初始化成功");
                    if (!gsmModem.InitPPPConnect())
                    {
                        break;
                    }
                    OnAddLog("拨号成功");
                    string uri = "/cmread/portalapi";
                    WebHeaderCollection httpHeader = new WebHeaderCollection();
                    httpHeader[HttpRequestHeader.Host] = "client.cmread.com";
                    httpHeader[HttpRequestHeader.UserAgent] = "CMREAD_Android_WH_V1.54_111104/240*320/neusoft001";
                    httpHeader["user-id"] = "2034d091006463c97db7bcd99a316542";
                    httpHeader["APIVersion"] = "1.0.0";
                    httpHeader["Action"] = "getCatalogInfo";
                    httpHeader["encoding-type"] = "gzip";
                    httpHeader["ClientHash"] = "oZdw0sa00WjrWUEf+wBCkA==";
                    //httpHeader[HttpRequestHeader.ContentType] = "application/xml";
                    httpHeader[HttpRequestHeader.Connection] = "Keep-Alive";
                    //string post = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<Request><Authenticate4Req><channel>00000000</channel><clientHash>oZdw0sa00WjrWUEf+wBCkA==</clientHash><cataloglist>true</cataloglist><systembookmark>false</systembookmark><catalogTimestamp>20120122093253</catalogTimestamp><includeResponse>true</includeResponse></Authenticate4Req></Request>";
                    //httpHeader[HttpRequestHeader.ContentLength] = post.Length.ToString();                    
                    CookieCollection cookies = new CookieCollection();
                    string tx = HttpStatic.HttpHeaderToStr(uri, httpHeader, cookies);
                    //tx = tx + post;
                    OnAddLog("进行登陆");
                    object o;                    
                    if (!gsmModem.TCPRead(new List<byte>(Encoding.ASCII.GetBytes(tx))))
                    {
                        OnAddLog("获得tcp数据失败!");
                        OnFinishEvent((int)FinishType.Unkown);
                        break;
                    }
                    o = gsmModem.TCPData.oTCPDatas;                    
                    if (o == null)
                        break;
                    Http http = (Http)o;
                    string str = "";
                    if (http.ContentDatas.Count == 0)
                        break;
                    str = HttpStatic.ContentToStr(http);
                    int x = str.IndexOf("onevent type=\"onenterforward\"");
                    if (x != -1)
                    {
                        x = str.IndexOf("go href=\"", x);
                        if (x != -1)
                        {
                            x += 9;
                            OnAddLog("获得跳转页");
                            httpHeader[HttpRequestHeader.Referer] = uri;
                            uri = WFNetLib.Strings.StringsFunction.strDecode(str.Substring(x, str.IndexOf('\"', x) - x));
                            if (http.Cookies.Count != 0)
                            {
                                foreach (Cookie c in http.Cookies)
                                {
                                    if (cookies[c.Name] != null)
                                        cookies[c.Name].Value = c.Value;
                                    else
                                        cookies.Add(c);
                                }
                            }
                            tx = HttpStatic.HttpHeaderToStr(uri, httpHeader, cookies);
                            if (!gsmModem.TCPRead(new List<byte>(Encoding.ASCII.GetBytes(tx))))
                            {
                                OnAddLog("获得tcp数据失败!");
                                OnFinishEvent((int)FinishType.Unkown);
                                break;
                            }

                            o = gsmModem.TCPData.oTCPDatas;
                        }
                    }
                    if (o == null)
                        break;
                    http = (Http)o;
                    OnAddLog("获得结果页");
                    str = HttpStatic.ContentToStr(http);
                    OnAddLog("断开连接");
                    if (!gsmModem.pppClose())
                    {
                        OnAddLog("ppp关闭失败");
                    }
                    else
                    {
                        OnAddLog("ppp关闭成功");
                    }
                    string PhoneNum = "";
                    string Ticket = "";
                    x = str.IndexOf("手机号码：");
                    if (x != -1)
                    {
                        x += "手机号码：".Length;
                        PhoneNum = str.Substring(x, 11);
                    }
                    else
                        PhoneNum = "未知手机号码";
                    OnAddLog("手机号码:" + PhoneNum);
                    x = str.IndexOf("书券余额:");
                    if (x != -1)
                    {
                        x += "书券余额:".Length;
                        Ticket = str.Substring(x, str.IndexOf("元", x) - x);
                        OnFinishEvent((int)FinishType.Finish, PhoneNum + ";" + Ticket);
                        OnAddLog("书券余额:" + Ticket);
                    }
                    else
                    {
                        OnFinishEvent((int)FinishType.UnkownTicket);
                        OnAddLog("未知书券余额:");
                    }
                    Com.Close();
                    return;
                }
                OnAddLog("<未知退出>");
                OnFinishEvent((int)FinishType.Unkown);
                Com.Close();
            }
            //              catch (System.Exception ex)
            //              {
            //                  if (!gsmModem.pppClose())
            //                  {
            //                      OnAddLog("ppp关闭失败");
            //                  }
            //                  else
            //                  {
            //                      OnAddLog("ppp关闭成功");
            //                  }
            //                  OnAddLog("<未知退出>"+ex.Message);
            //                  OnFinishEvent((int)FinishType.Unkown);
            //                  Com.Close();
            //              }

        }
    }
    public enum FinishType
    {
        Finish = 0,
        Unkown = 1,
        UnkownTicket = 2
    }
}
